from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from .config import Config
import os

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__, 
                template_folder='../templates',  # 指定模板目录
                static_folder='../static',       # 确保这里指向正确的目录
                static_url_path='/static')       # 添加这行
    app.config.from_object(config_class)

    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)

    # 设置登录视图
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    login_manager.login_message_category = 'info'

    # 注册蓝图
    from .routes import auth_bp, main_bp, user_bp
    from .routes.pathogen import pathogen_bp
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)
    app.register_blueprint(pathogen_bp, url_prefix='/pathogen')
    app.register_blueprint(user_bp, url_prefix='/user')

    # Windows 风格的路径处理
    reports_dir = os.path.join(app.root_path, 'static', 'reports')
    reports_dir = os.path.normpath(reports_dir)  # 标准化路径
    if not os.path.exists(reports_dir):
        os.makedirs(reports_dir)
    
    return app 